{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting data/train-images-idx3-ubyte.gz\n",
      "Extracting data/train-labels-idx1-ubyte.gz\n",
      "Extracting data/t10k-images-idx3-ubyte.gz\n",
      "Extracting data/t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import matplotlib.pyplot as plt\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "%matplotlib inline\n",
    "mnist = input_data.read_data_sets('data/', one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Use Logistic Regression from our previous example\n",
    "\n",
    "# Parameters\n",
    "learning_rate = 0.01\n",
    "training_epochs = 10\n",
    "batch_size = 100\n",
    "display_step = 1\n",
    "\n",
    "# tf Graph Input\n",
    "x = tf.placeholder(\"float\", [None, 784], name='x') # mnist data image of shape 28*28=784\n",
    "y = tf.placeholder(\"float\", [None, 10], name='y') # 0-9 digits recognition => 10 classes\n",
    "\n",
    "# Create model\n",
    "\n",
    "# Set model weights\n",
    "W = tf.Variable(tf.zeros([784, 10]), name=\"weights\")\n",
    "b = tf.Variable(tf.zeros([10]), name=\"bias\")\n",
    "\n",
    "# Construct model\n",
    "activation = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax\n",
    "\n",
    "# Minimize error using cross entropy\n",
    "cost = -tf.reduce_sum(y*tf.log(activation)) # Cross entropy\n",
    "optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) # Gradient Descent\n",
    "\n",
    "# Initializing the variables\n",
    "init = tf.initialize_all_variables()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch: 0001 cost= 29.860462506\n",
      "Epoch: 0002 cost= 22.028559675\n",
      "Epoch: 0003 cost= 21.019104078\n",
      "Epoch: 0004 cost= 20.528993900\n",
      "Epoch: 0005 cost= 20.129545855\n",
      "Epoch: 0006 cost= 19.980496155\n",
      "Epoch: 0007 cost= 19.713256450\n",
      "Epoch: 0008 cost= 19.486078643\n",
      "Epoch: 0009 cost= 19.291432394\n",
      "Epoch: 0010 cost= 19.155823388\n",
      "Optimization Finished!\n",
      "Accuracy: 0.9236\n"
     ]
    }
   ],
   "source": [
    "# Launch the graph\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init)\n",
    "\n",
    "    # Set logs writer into folder /tmp/tensorflow_logs\n",
    "    summary_writer = tf.train.SummaryWriter('/tmp/tensorflow_logs', graph=sess.graph)\n",
    "\n",
    "    # Training cycle\n",
    "    for epoch in range(training_epochs):\n",
    "        avg_cost = 0.\n",
    "        total_batch = int(mnist.train.num_examples/batch_size)\n",
    "        # Loop over all batches\n",
    "        for i in range(total_batch):\n",
    "            batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n",
    "            # Fit training using batch data\n",
    "            sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})\n",
    "            # Compute average loss\n",
    "            avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})/total_batch\n",
    "        # Display logs per epoch step\n",
    "        if epoch % display_step == 0:\n",
    "            print \"Epoch:\", '%04d' % (epoch+1), \"cost=\", \"{:.9f}\".format(avg_cost)\n",
    "\n",
    "    print \"Optimization Finished!\"\n",
    "\n",
    "    # Test model\n",
    "    correct_prediction = tf.equal(tf.argmax(activation, 1), tf.argmax(y, 1))\n",
    "    # Calculate accuracy\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n",
    "    print \"Accuracy:\", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "### Run the command line\n",
    "##### tensorboard --logdir=/tmp/tensorflow_logs\n",
    "### Open http://localhost:6006/ into your web browser"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
